<template>
  <el-dialog draggable title="添加成员" :close-on-click-modal="false" class="yy-modal--custom yy-item-member" width="800px" v-model="isVisible" @close="onCancelModel" :show-close="true">
    <div class="yy-item-member_empl">
      <span style="margin-right: 8px;">选择医生: </span>
      <el-select ref="employeeSelectorRef" v-model="selectEmployee"
                 filterable
                 reserve-keyword
                 multiple
                 remote
                 remote-show-suffix
                 :remote-method="getEmployeeList"
                 automatic-dropdown
                 placeholder="输入关键字搜索"
                 style="width: 100%"
                 @change="onSelectEmployeeChange"
      >
        <el-option
            v-for="item in employeeList"
            :key="item.id"
            :label="item.name + `(${item.code})`"
            :value="item.id"
        />
      </el-select>
    </div>
    <div class="yy-item-member_table">
      <el-table
          :data="table.data"
          style="width: 100%;"
          border
      >
        <template v-for="column in table.columns" :key="column.field">
          <el-table-column
              v-if="column.showable && ((!column.condition && column != false) || column.condition(column))"
              :type="column.type"
              :property="column.field"
              :label="typeOf(column.label) == 'function' ? column.label() : column.label"
              :width="column.width"
              :min-width="column.minWidth || 120"
              :align="column.align"
              :fixed="column.fixed || false"
              :sortable="column.sortable"
          >
            <template #default="scope">
              <div v-if="column.field === 'categoryId'">
                <el-select  v-model="scope.row[column.field]" placeholder="请选择挂号类目" style="width: 100%;">
                  <el-option :label="op.name" :value="op.id" v-for="op in table.categories" :key="op.id"/>
                </el-select>
              </div>
              <div v-else-if="column.field === 'price'">
                <el-input-number v-model="scope.row[column.field]" placeholder="请输入挂号价格" style="width: 100%;"/>
              </div>
              <div v-else-if="column.field === 'action'">
                <el-button size="small" type="primary" @click="onCopy(scope.row)">复制</el-button>
                <el-button size="small" type="danger" @click="onRemove(scope.row)">移除</el-button>
              </div>
              <div v-else> {{scope.row[column.field]}}</div>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>

    <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancelModel">关闭</el-button>
          <el-button type="primary" :loading="isSubmit" @click="onSave">保存</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">

import {defineExpose, defineEmits, reactive, ref} from "vue";
import {formatDate, typeOf} from "@/utils/yayi";
import {debounce} from "@/utils";
import {TableColumn} from "@/model/Definition";
import {QueueItemEmplModel} from "@/model/QueueItemEmplModel";
import {useRoute} from "vue-router";
import RegCategoryApi from "@/api/queue/RegCategoryApi";
import {QueueRegCategoryModel} from "@/model/QueueRegCategoryModel";
import RegItemApi from "@/api/queue/RegItemApi";
import {ElMessage} from "element-plus";
import EmployeeApi from "@/api/system/empl";

let emplSearchInterval = null

const route = useRoute()
const $emit = defineEmits({
  saveSuccess: () => true
})

const isVisible = ref(false)
const isSubmit = ref(false)
const employeeList = ref([])
const selectEmployee = ref([])
const employeeSelectorRef = ref()

const table = reactive<{
  loading: boolean,
  categories: QueueRegCategoryModel[],
  columns: TableColumn[],
  data: QueueItemEmplModel[],
  formats?: any
}>({
  loading: false,
  categories: [],
  columns: [
    {
      field: 'emplName',
      label: '姓名',
      showable: true
    },{
      field: 'emplLevelName',
      label: '职级',
      showable: true
    }, {
      field: 'categoryId',
      label: '挂号类目',
      showable: true
    }, {
      field: 'price',
      label: '挂号价格',
      showable: true
    }, {
      field: 'action',
      label: '操作',
      width: 145,
      showable: true
    }
  ],
  data: [],
})

const onShowDialog = () => {
  isVisible.value = true
  getItemEmployee()
  getEmployeeList()
  getCategoryList()
}

const getItemEmployee = () => {
  table.loading = true
  RegItemApi.listEmployeeByItem(route.query.itemId as string, route.query.deptId as string).then(data => {
    table.data = data
    table.loading = false
  }, () => {
    table.loading = false
  })
}

const getEmployeeList = () => {
  EmployeeApi.listByDepartId(route.query.deptId as string).then((res) => {
    employeeList.value = res
  })
}

const getCategoryList = () => {
  RegCategoryApi.listRegCategory().then((data) => {
    table.categories = data
  })
}

const onSelectEmployeeChange = () => {
  let tableData = table.data
  for(let emplId of selectEmployee.value) {
    const index = tableData.findIndex(it => it.emplId === emplId)
    if (index < 0) {
      const empl = employeeList.value.find(empl => empl.id === emplId)
      tableData.push(new QueueItemEmplModel().deserialize({
        id: new Date().getTime() + "_" + Math.random(),
        itemId: route.query.itemId,
        deptId: route.query.deptId,
        emplId: empl.id,
        emplCode: empl.code,
        emplLevelName: empl.levelName,
        emplName: empl.name,
        categoryId: null,
        price: 0
      }))
      console.log('--------on select-------------', tableData, route.query.deptId)
    }
  }
  // remove items
  // tableData = tableData.filter(item => selectEmployee.value.includes(item.emplId))
  table.data = tableData
}

const onCancelModel = () => {
  isVisible.value = false
  selectEmployee.value = []
}

const onCopy = (row: QueueItemEmplModel) => {
  const index = table.data.findIndex(item => item.id === row.id)
  table.data.splice(index, 0, new QueueItemEmplModel().deserialize(Object.assign({}, row, {id: new Date().getTime() + "_" + Math.random()})))
}

const onRemove = (row: QueueItemEmplModel) => {
  const index = table.data.findIndex(item => item.id === row.id)
  table.data.splice(index, 1)
}

const onSave = () => {
  isSubmit.value = true
  const addEmplItems = table.data.map(item => new QueueItemEmplModel().deserialize({
    id: item.id && !item.id.includes("_") ? item.id : undefined,
    itemId: item.itemId,
    emplId: item.emplId,
    deptId: item.deptId,
    categoryId: item.categoryId,
    price: item.price
  }))
  RegItemApi.addEmployeeToItem(route.query.deptId as string, route.query.itemId as string, addEmplItems).then(res => {
    ElMessage.success({
      message: '成员保存成功',
      showClose: true
    })
    isSubmit.value = false
    $emit('saveSuccess')
    onCancelModel()
  }, () => isSubmit.value = false)
}
defineExpose({
  onShowDialog
})
</script>
<style scoped lang="scss">
.yy-item-member {
  &_empl {
    margin-bottom: 15px;
    display: flex;
    white-space: nowrap;
    align-items: center;
    background: #f5f7fa;
    padding: 8px 15px;
  }
  &_table {
    :deep(.el-table__cell) {
      padding: 5px !important;
    }
  }
}
</style>